'''
This file is part of Lampy.

Lampy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Lampy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Lampy.  If not, see <http://www.gnu.org/licenses/>.

Copyright 2011 Kevin Han
'''

"""Functions to convert from integers to Church numerals and vice versa."""
from utils import *

def counter(start=0):
    """Return generator counting up by 1 forever."""
    i = start
    while True:
        yield i
        i += 1

def toNode(i):
    """Return node representation of integer i."""
    l = 'x'
    for j in xrange(i):
        l = ['f', l]
    return ['/fx', l]

def fromNode(node):
    """
    Return integer represented by node, or None if not an integer.

    >>> fromNode(['/ab', 'b'])
    0
    >>> fromNode(['/bc', ['b', ['b', ['b', 'c']]]])
    3
    >>> print fromNode(['/bc', ['b', ['b', ['c', 'c']]]])
    None
    >>> print fromNode(['/bc', ['b', ['b', ['b', 'b']]]])
    None
    """
    if not isFunc(node):
        return None

    params, body = splitFunc(node)
    try:
        f, x = params
    except ValueError:
        return None

    if body == x:
        return 0

    for i in counter(1):
        if body[0] != f or len(body) != 2:
            return None
        if body[1] == x:
            return i
        body = body[1]
    
    return None

if __name__ == '__main__':
    import doctest

    doctest.testmod()
